package com.example.pets.model.entities.database;

import static android.content.Context.MODE_PRIVATE;

import android.content.SharedPreferences;

import com.example.pets.MapApplication;
import com.example.pets.model.entities.Pet;
import com.example.pets.model.entities.User;
import com.google.gson.Gson;

public class ShareprefenseUtil {


    private final SharedPreferences sharedPreferences;
    private final SharedPreferences.Editor editor;

    public static ShareprefenseUtil instanse;
    public static ShareprefenseUtil getinstanse(){
        if (instanse==null){
            instanse=new ShareprefenseUtil();
        }
        return instanse;
    }
    public ShareprefenseUtil(){
        // 使用 getSharedPreferences
         sharedPreferences = MapApplication.mContext.getSharedPreferences("MyPref", MODE_PRIVATE);
         editor = sharedPreferences.edit();
    }

    public  void  insertpet(Pet pet){
        Gson gson = new Gson();
        String json=gson.toJson(pet);
        editor.putString("pet", json);
        editor.apply();
    }

    public Pet getpet(){
        String s=sharedPreferences.getString("pet","");
        if(!s.isEmpty()){
            Gson gson = new Gson();
            Pet pet = gson.fromJson(s, Pet.class);
            return pet;
        }else {
            return null;
        }

    }
    public  void  insertLoginUser(User user){
        Gson gson = new Gson();
        String json=gson.toJson(user);
        editor.putString("loginuser", json);
        editor.putBoolean("islogin",true);
        editor.apply();
    }

    public void login(){
        editor.putBoolean("islogin",true);
        editor.apply();
    }

    public void logout(){
        editor.putBoolean("islogin",false);
        editor.apply();
    }

    public User getLoginUser(){
        String s=sharedPreferences.getString("loginuser","");
        Gson gson = new Gson();
        User user = gson.fromJson(s, User.class);
        return user;
    }
    public boolean islogin(){
        return sharedPreferences.getBoolean("islogin",false);
    }


}
